package com.smartcruise.start.loginActivity;

import android.text.TextUtils;

import com.smartcruise.R;
import com.smartcruise.data.UserInfo;
import com.smartcruise.util.SPUtils;
import com.smartcruise.util.network.callBack.SimpleCallBack;
import com.smartcruise.util.network.netUtils.NetCollection;
import com.smartcruise.util.network.netUtils.Result;

import io.realm.Realm;

/**
 * Created by FengChaoQun
 * on 2018/1/18 0018
 */

public class LoginPresenterImp implements LoginContract.Presenter {

    private LoginContract.View mView;

    public LoginPresenterImp(LoginContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void login() {
        if (TextUtils.isEmpty(mView.getAccount()) || TextUtils.isEmpty(mView.getPassword())) {
            mView.showToast(R.string.pleaseInputWholeLoginInfo);
        } else {
            NetCollection.login(mView.getAccount(), mView.getPassword(), mView, new SimpleCallBack(mView) {
                @Override
                public void onSuccess(final Result result) {
                    //将用户信息存储到本地
                    mView.getRealm().executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            UserInfo userInfo = realm.createOrUpdateObjectFromJson(UserInfo.class, result.getData());
                            SPUtils.saveAccount(userInfo.getId());
                            SPUtils.saveToken(userInfo.getToken());
                            SPUtils.saveName(userInfo.getUserName());
                            SPUtils.savePhone(userInfo.getPhoneNumber());
                        }
                    });
                    mView.gotoMainActivity();
                }
            });
        }
    }

    /**
     * description:如果本地存储有账号 则自动填充
     */

    @Override
    public void start() {
        mView.setAccount(SPUtils.getLastPhone());
    }
}
